<template>
<div class="follows-container">
    <!-- 使用通用导航栏组件 -->
    <tab-nav-bar :tabs="navTabs" :active-tab="activeTab" @click-left="$router.back()" @tab-change="switchTab" />

    <!-- 搜索框 -->
    <div class="search-box">
        <van-search v-model="searchText" :placeholder="searchPlaceholder" shape="round" background="#f7f8fa" />
    </div>

    <!-- 内容区域 -->
    <div class="tab-content">
        <!-- 互相关注 -->
        <div v-show="activeTab === 'mutual'" class="tab-pane">
            <div class="follows-list">
                <div v-for="(user, index) in filteredMutualList" :key="index" class="follow-item">
                    <div class="user-avatar" @click="goToUserProfile(user.userId)">
                        <img :src="user.avatar" alt="avatar" />
                    </div>
                    <div class="user-info" @click="goToUserProfile(user.userId)">
                        <div class="user-name">{{ user.nickname }}</div>
                        <div class="user-desc">{{ user.description || '这个人很懒，什么都没写~' }}</div>
                        <div class="user-stats" v-if="user.stats">
                            <span>笔记 {{ user.stats.posts }}</span>
                            <span class="stat-divider">|</span>
                            <span>粉丝 {{ user.stats.followers }}</span>
                        </div>
                    </div>
                    <div class="follow-action">
                        <van-button size="small" type="default" round class="followed-btn" @click="toggleFollow(user)">
                            互相关注
                        </van-button>
                    </div>
                </div>

                <!-- 加载更多 -->
                <div class="load-more" v-if="mutualHasMore">
                    <van-loading size="24px" type="spinner">加载中...</van-loading>
                </div>

                <!-- 无数据提示 -->
                <div class="empty-list" v-if="filteredMutualList.length === 0">
                    <van-empty description="暂无互相关注" />
                </div>
            </div>
        </div>

        <!-- 关注 -->
        <div v-show="activeTab === 'following'" class="tab-pane">
            <!-- 分类筛选 -->
            <div class="filter-tabs">
                <div class="filter-header">
                    <div class="filter-left">
                        <div class="filter-item" :class="{ active: followingFilter === 'all' }"
                            @click="setFollowingFilter('all')">
                            全部
                        </div>
                        <div class="filter-item" :class="{ active: followingFilter === 'business' }"
                            @click="setFollowingFilter('business')">
                            商家
                        </div>
                    </div>
                    <div class="filter-right">
                        <span>我的关注 ({{ followingList.length }})</span>
                        <van-icon name="arrow-down" size="14" />
                    </div>
                </div>
            </div>

            <div class="follows-list">
                <div v-for="(user, index) in filteredFollowingList" :key="index" class="follow-item">
                    <div class="user-avatar" @click="goToUserProfile(user.userId)">
                        <img :src="user.avatar" alt="avatar" />
                    </div>
                    <div class="user-info" @click="goToUserProfile(user.userId)">
                        <div class="user-name">{{ user.nickname }}</div>
                        <div class="user-desc">{{ user.description || '这个人很懒，什么都没写~' }}</div>
                        <div class="user-stats" v-if="user.stats">
                            <span>笔记 {{ user.stats.posts }}</span>
                            <span class="stat-divider">|</span>
                            <span>粉丝 {{ user.stats.followers }}</span>
                        </div>
                    </div>
                    <div class="follow-action">
                        <van-button size="small" :type="user.isFollowed ? 'default' : 'primary'" round
                            :class="{ 'followed-btn': user.isFollowed, 'follow-btn': !user.isFollowed }"
                            @click="toggleFollow(user)">
                            {{ user.isFollowed ? '已关注' : '关注' }}
                        </van-button>
                    </div>
                </div>

                <!-- 加载更多 -->
                <div class="load-more" v-if="followingHasMore">
                    <van-loading size="24px" type="spinner">加载中...</van-loading>
                </div>

                <!-- 无数据提示 -->
                <div class="empty-list" v-if="filteredFollowingList.length === 0">
                    <van-empty description="暂无关注" />
                </div>
            </div>
        </div>

        <!-- 粉丝 -->
        <div v-show="activeTab === 'followers'" class="tab-pane">
            <!-- 粉丝统计 -->
            <div class="filter-tabs">
                <div class="filter-header">
                    <div class="filter-right">
                        <span>我的粉丝 ({{ followersList.length }})</span>
                        <van-icon name="arrow-down" size="14" />
                    </div>
                </div>
            </div>

            <div class="follows-list">
                <div v-for="(user, index) in filteredFollowersList" :key="index" class="follow-item">
                    <div class="user-avatar" @click="goToUserProfile(user.userId)">
                        <img :src="user.avatar" alt="avatar" />
                    </div>
                    <div class="user-info" @click="goToUserProfile(user.userId)">
                        <div class="user-name">{{ user.nickname }}</div>
                        <div class="user-desc">{{ user.description || '这个人很懒，什么都没写~' }}</div>
                        <div class="user-stats" v-if="user.stats">
                            <span>笔记 {{ user.stats.posts }}</span>
                            <span class="stat-divider">|</span>
                            <span>粉丝 {{ user.stats.followers }}</span>
                        </div>
                    </div>
                    <div class="follow-action">
                        <van-button size="small" :type="user.isFollowed ? 'default' : 'primary'" round
                            :class="{ 'followed-btn': user.isFollowed, 'follow-btn': !user.isFollowed }"
                            @click="toggleFollow(user)">
                            {{ user.isFollowed ? '互相关注' : '关注' }}
                        </van-button>
                    </div>
                </div>

                <!-- 加载更多 -->
                <div class="load-more" v-if="followersHasMore">
                    <van-loading size="24px" type="spinner">加载中...</van-loading>
                </div>

                <!-- 无数据提示 -->
                <div class="empty-list" v-if="filteredFollowersList.length === 0">
                    <van-empty description="暂无粉丝" />
                </div>
            </div>
        </div>

        <!-- 推荐 -->
        <div v-show="activeTab === 'recommend'" class="tab-pane">
            <!-- 分类筛选 -->
            <div class="filter-tabs">
                <div class="filter-header">
                    <div class="filter-left">
                        <div class="filter-item" :class="{ active: recommendFilter === 'all' }"
                            @click="setRecommendFilter('all')">
                            全部
                        </div>
                        <div class="filter-item" :class="{ active: recommendFilter === 'hot' }"
                            @click="setRecommendFilter('hot')">
                            热门
                        </div>
                    </div>
                    <div class="filter-right">
                        <span>推荐用户 ({{ recommendList.length }})</span>
                        <van-icon name="arrow-down" size="14" />
                    </div>
                </div>
            </div>

            <div class="follows-list">
                <div v-for="(user, index) in filteredRecommendList" :key="index" class="follow-item">
                    <div class="user-avatar" @click="goToUserProfile(user.userId)">
                        <img :src="user.avatar" alt="avatar" />
                    </div>
                    <div class="user-info" @click="goToUserProfile(user.userId)">
                        <div class="user-name">{{ user.nickname }}</div>
                        <div class="user-desc">{{ user.description || '这个人很懒，什么都没写~' }}</div>
                        <div class="user-stats" v-if="user.stats">
                            <span>笔记 {{ user.stats.posts }}</span>
                            <span class="stat-divider">|</span>
                            <span>粉丝 {{ user.stats.followers }}</span>
                        </div>
                    </div>
                    <div class="follow-action">
                        <van-button size="small" :type="user.isFollowed ? 'default' : 'primary'" round
                            :class="{ 'followed-btn': user.isFollowed, 'follow-btn': !user.isFollowed }"
                            @click="toggleFollow(user)">
                            {{ user.isFollowed ? '已关注' : '关注' }}
                        </van-button>
                    </div>
                </div>

                <!-- 加载更多 -->
                <div class="load-more" v-if="recommendHasMore">
                    <van-loading size="24px" type="spinner">加载中...</van-loading>
                </div>

                <!-- 无数据提示 -->
                <div class="empty-list" v-if="filteredRecommendList.length === 0">
                    <van-empty description="暂无推荐" />
                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
import { mapGetters } from 'vuex'
import TabNavBar from '@/components/TabNavBar.vue'

export default {
    name: 'FollowsPage',
    components: {
        TabNavBar
    },
    data() {
        return {
            activeTab: 'mutual', // 默认显示互相关注
            searchText: '', // 搜索文本

            // 导航栏选项卡数据
            navTabs: [
                { label: '互相关注', value: 'mutual' },
                { label: '关注', value: 'following' },
                { label: '粉丝', value: 'followers' },
                { label: '推荐', value: 'recommend' }
            ],

            // 互相关注
            mutualList: [],
            mutualHasMore: false,
            mutualPage: 1,
            mutualPageSize: 10,

            // 关注
            followingList: [],
            followingFilter: 'all',
            followingHasMore: false,
            followingPage: 1,
            followingPageSize: 10,

            // 粉丝
            followersList: [],
            followersHasMore: false,
            followersPage: 1,
            followersPageSize: 10,

            // 推荐
            recommendList: [],
            recommendFilter: 'all',
            recommendHasMore: false,
            recommendPage: 1,
            recommendPageSize: 10,

            loading: false
        }
    },
    beforeCreate() {
        // 确保在Vue实例初始化前有基本的数据
        this._initialData = {
            activeTab: 'mutual',
            searchText: '',
            mutualList: [],
            mutualHasMore: false,
            filteredMutualList: [],
            searchPlaceholder: '搜索用户'
        }
    },
    created() {
        // 根据路由参数设置当前标签
        const type = this.$route.params.type
        if (type && ['mutual', 'following', 'followers', 'recommend'].includes(type)) {
            this.activeTab = type
        }

        // 加载当前标签的数据
        this.loadCurrentTabData()
    },
    computed: {
        ...mapGetters(['followedUsers']),

        // 搜索框占位符
        searchPlaceholder() {
            switch (this.activeTab) {
                case 'mutual':
                    return '搜索互相关注的人'
                case 'following':
                    return '搜索已关注的人'
                case 'followers':
                    return '搜索粉丝'
                case 'recommend':
                    return '搜索推荐用户'
                default:
                    return '搜索用户'
            }
        },

        // 互相关注列表过滤
        filteredMutualList() {
            let list = this.mutualList || []

            // 搜索过滤
            if (this.searchText) {
                const keyword = this.searchText.toLowerCase()
                list = list.filter(user =>
                    user.nickname.toLowerCase().includes(keyword) ||
                    (user.description && user.description.toLowerCase().includes(keyword))
                )
            }

            return list
        },

        // 关注列表过滤
        filteredFollowingList() {
            let list = this.followingList || []

            // 搜索过滤
            if (this.searchText) {
                const keyword = this.searchText.toLowerCase()
                list = list.filter(user =>
                    user.nickname.toLowerCase().includes(keyword) ||
                    (user.description && user.description.toLowerCase().includes(keyword))
                )
            }

            // 分类过滤
            if (this.followingFilter === 'business') {
                list = list.filter(user => user.isBusiness)
            }

            return list
        },

        // 粉丝列表过滤
        filteredFollowersList() {
            let list = this.followersList || []

            // 搜索过滤
            if (this.searchText) {
                const keyword = this.searchText.toLowerCase()
                list = list.filter(user =>
                    user.nickname.toLowerCase().includes(keyword) ||
                    (user.description && user.description.toLowerCase().includes(keyword))
                )
            }

            return list
        },

        // 推荐列表过滤
        filteredRecommendList() {
            let list = this.recommendList || []

            // 搜索过滤
            if (this.searchText) {
                const keyword = this.searchText.toLowerCase()
                list = list.filter(user =>
                    user.nickname.toLowerCase().includes(keyword) ||
                    (user.description && user.description.toLowerCase().includes(keyword))
                )
            }

            // 分类过滤
            if (this.recommendFilter === 'hot') {
                list = list.filter(user => user.isHot)
            }

            return list
        }
    },
    methods: {
        // 切换标签
        switchTab(tab) {
            if (this.activeTab === tab) return
            this.activeTab = tab
            this.searchText = ''

            // 加载当前标签的数据
            this.loadCurrentTabData()
        },

        // 加载当前标签的数据
        loadCurrentTabData() {
            switch (this.activeTab) {
                case 'mutual':
                    if (this.mutualList.length === 0) {
                        this.fetchMutualList()
                    }
                    break
                case 'following':
                    if (this.followingList.length === 0) {
                        this.fetchFollowingList()
                    }
                    break
                case 'followers':
                    if (this.followersList.length === 0) {
                        this.fetchFollowersList()
                    }
                    break
                case 'recommend':
                    if (this.recommendList.length === 0) {
                        this.fetchRecommendList()
                    }
                    break
            }
        },

        // 设置关注列表筛选
        setFollowingFilter(filter) {
            this.followingFilter = filter
        },

        // 设置推荐列表筛选
        setRecommendFilter(filter) {
            this.recommendFilter = filter
        },

        // 跳转到用户主页
        goToUserProfile(userId) {
            this.$router.push(`/user/${userId}`)
        },

        // 切换关注状态
        toggleFollow(user) {
            // 调用 Vuex action
            this.$store.commit('toggleFollowUser', user.userId)

            // 更新本地状态
            user.isFollowed = !user.isFollowed
        },

        // 获取互相关注列表
        async fetchMutualList() {
            if (this.loading || (this.mutualList.length > 0 && !this.mutualHasMore)) return

            this.loading = true

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const mockData = Array(10).fill().map((_, index) => ({
                        userId: `mutual_${this.mutualPage}_${index}`,
                        nickname: `互相关注用户${this.mutualPage}_${index}`,
                        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                        description: `这是互相关注用户的个人简介 ${this.mutualPage}_${index}`,
                        isFollowed: true,
                        stats: {
                            posts: Math.floor(Math.random() * 100),
                            followers: Math.floor(Math.random() * 1000)
                        }
                    }))

                    this.mutualList = [...this.mutualList, ...mockData]
                    this.mutualPage += 1
                    this.mutualHasMore = this.mutualPage < 5 // 模拟有5页数据
                    this.loading = false
                }, 1000)
            } catch (error) {
                console.error('获取互相关注列表失败', error)
                this.loading = false
            }
        },

        // 获取关注列表
        async fetchFollowingList() {
            if (this.loading || (this.followingList.length > 0 && !this.followingHasMore)) return

            this.loading = true

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const mockData = Array(10).fill().map((_, index) => ({
                        userId: `following_${this.followingPage}_${index}`,
                        nickname: `关注用户${this.followingPage}_${index}`,
                        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                        description: `这是关注用户的个人简介 ${this.followingPage}_${index}`,
                        isFollowed: true,
                        isBusiness: index % 3 === 0, // 每3个有1个是商家
                        stats: {
                            posts: Math.floor(Math.random() * 100),
                            followers: Math.floor(Math.random() * 1000)
                        }
                    }))

                    this.followingList = [...this.followingList, ...mockData]
                    this.followingPage += 1
                    this.followingHasMore = this.followingPage < 5 // 模拟有5页数据
                    this.loading = false
                }, 1000)
            } catch (error) {
                console.error('获取关注列表失败', error)
                this.loading = false
            }
        },

        // 获取粉丝列表
        async fetchFollowersList() {
            if (this.loading || (this.followersList.length > 0 && !this.followersHasMore)) return

            this.loading = true

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const mockData = Array(10).fill().map((_, index) => ({
                        userId: `follower_${this.followersPage}_${index}`,
                        nickname: `粉丝用户${this.followersPage}_${index}`,
                        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                        description: `这是粉丝用户的个人简介 ${this.followersPage}_${index}`,
                        isFollowed: index % 2 === 0, // 一半已关注
                        stats: {
                            posts: Math.floor(Math.random() * 100),
                            followers: Math.floor(Math.random() * 1000)
                        }
                    }))

                    this.followersList = [...this.followersList, ...mockData]
                    this.followersPage += 1
                    this.followersHasMore = this.followersPage < 5 // 模拟有5页数据
                    this.loading = false
                }, 1000)
            } catch (error) {
                console.error('获取粉丝列表失败', error)
                this.loading = false
            }
        },

        // 获取推荐列表
        async fetchRecommendList() {
            if (this.loading || (this.recommendList.length > 0 && !this.recommendHasMore)) return

            this.loading = true

            try {
                // 模拟API请求
                setTimeout(() => {
                    // 模拟数据
                    const mockData = Array(10).fill().map((_, index) => ({
                        userId: `recommend_${this.recommendPage}_${index}`,
                        nickname: `推荐用户${this.recommendPage}_${index}`,
                        avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
                        description: `这是推荐用户的个人简介 ${this.recommendPage}_${index}`,
                        isFollowed: index % 4 === 0, // 每4个有1个已关注
                        isHot: index % 3 === 0, // 每3个有1个是热门
                        stats: {
                            posts: Math.floor(Math.random() * 100),
                            followers: Math.floor(Math.random() * 1000)
                        }
                    }))

                    this.recommendList = [...this.recommendList, ...mockData]
                    this.recommendPage += 1
                    this.recommendHasMore = this.recommendPage < 5 // 模拟有5页数据
                    this.loading = false
                }, 1000)
            } catch (error) {
                console.error('获取推荐列表失败', error)
                this.loading = false
            }
        }
    },
    watch: {
        // 监听路由参数变化
        '$route.params.type': function (newType) {
            if (newType && ['mutual', 'following', 'followers', 'recommend'].includes(newType)) {
                this.activeTab = newType;
                this.loadCurrentTabData();
            }
        }
    }
}
</script>

<style scoped>
.follows-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f7f8fa;
}

.tab-header {
    display: flex;
    width: 100%;
    justify-content: space-around;
}

.tab-item {
    padding: 0 6px;
    font-size: 14px;
    color: #666;
    position: relative;
}

.tab-item.active {
    color: #333;
    font-weight: 500;
}

.tab-item.active::after {
    content: '';
    position: absolute;
    bottom: -8px;
    left: 50%;
    transform: translateX(-50%);
    width: 16px;
    height: 2px;
    background-color: #fe496d;
    border-radius: 2px;
}

.search-box {
    padding: 8px 16px;
    background-color: #fff;
    position: sticky;
    top: 46px;
    z-index: 10;
}

.tab-content {
    flex: 1;
    overflow-y: auto;
}

.tab-pane {
    padding-bottom: 60px;
}

.follows-list {
    background-color: #fff;
    padding: 0 16px;
}

.follow-item {
    display: flex;
    padding: 16px 0;
    border-bottom: 1px solid #f5f5f5;
}

.follow-item:last-child {
    border-bottom: none;
}

.user-avatar {
    width: 48px;
    height: 48px;
    margin-right: 12px;
}

.user-avatar img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
}

.user-info {
    flex: 1;
    overflow: hidden;
}

.user-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.user-desc {
    font-size: 13px;
    color: #999;
    margin-bottom: 6px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
}

.user-stats {
    font-size: 12px;
    color: #999;
}

.stat-divider {
    margin: 0 6px;
    color: #eee;
}

.follow-action {
    display: flex;
    align-items: center;
    margin-left: 12px;
}

.follow-btn {
    background-color: #fe496d;
    border: none;
    color: #fff;
}

.followed-btn {
    background-color: #f5f5f5;
    border: none;
    color: #666;
}

.filter-tabs {
    padding: 12px 16px;
    background-color: #fff;
    margin-bottom: 8px;
}

.filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.filter-left {
    display: flex;
}

.filter-item {
    margin-right: 16px;
    font-size: 14px;
    color: #666;
    padding-bottom: 4px;
    position: relative;
}

.filter-item.active {
    color: #333;
    font-weight: 500;
}

.filter-item.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #fe496d;
    border-radius: 2px;
}

.filter-right {
    font-size: 13px;
    color: #999;
    display: flex;
    align-items: center;
}

.filter-right .van-icon {
    margin-left: 4px;
}

.load-more {
    text-align: center;
    padding: 16px 0;
    color: #999;
}

.empty-list {
    padding: 60px 0;
}
</style>